import { Injectable, Logger } from '@nestjs/common'

import dayjs from 'dayjs'

import Redis from 'ioredis'
import { DataSource } from 'typeorm'
import { InjectRedis } from '~/common/decorators/inject-redis.decorator'
import { HomeCountDto, SportCountDto } from '~/modules/health/data/data.dto'

import { DictItemService } from '~/modules/system/dict-item/dict-item.service'
import { DeviceService } from '../device/device.service'
import { UserAlarmService } from '../user/userAlarm.service'
import { UserDataService } from '../user/userData.service'
import { UserSosService } from '../user/userSos.service'

@Injectable()
export class DataService {
  private logger = new Logger(DataService.name)

  constructor(
    private readonly dataSource: DataSource,
    private deviceService: DeviceService,
    private userDataService: UserDataService,
    private userAlarmService: UserAlarmService,
    private userSosService: UserSosService,
    private dictItemService: DictItemService,
    @InjectRedis() private readonly redis: Redis,
  ) { }

  async homeCount(): Promise<HomeCountDto> {
    const data = await this.dataSource.query(
      `SELECT
            ( SELECT COUNT( 1 ) FROM sys_user_roles WHERE role_id = ? ) AS userCount,
            ( SELECT COUNT( 1 ) FROM health_device ) AS deviceCount,
            ( SELECT SUM(data->'$.value') FROM health_user_data WHERE type = ?) AS heatCount,
            ( SELECT COUNT( 1 ) FROM health_user_alarm WHERE status = ?) AS alarmCount,
            ( SELECT COUNT( 1 ) FROM health_user_sos WHERE status = ?) AS sosCount`,
      [9, 2, 0, 0],
    )
    return (data && data[0]) as HomeCountDto
  }

  async sportCount(): Promise<SportCountDto[]> {
    const data = await this.dataSource.query(`
      SELECT 
        DATE(ts) AS date,
        SUM(CASE WHEN type = 2 THEN data->'$.value' ELSE 0 END) AS heat,
        SUM(CASE WHEN type = 3 THEN data->'$.value' ELSE 0 END) AS dist
      FROM 
        health_user_data
      WHERE 
        (type = 2 OR type = 3)
        AND ts >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH)
      GROUP BY DATE(ts)`, [])

    data.forEach((item) => {
      item.date = dayjs(item.date).format('YYYY-MM-DD')
    })
    return data as SportCountDto[]
  }
}
